#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
#include <iostream>
#include <vector>
#include <fstream>
#include <math.h>
#include <stdlib.h>
#include "objModel.h"

void    nextNum(std::string& str)
{
    str.erase(0,str.find(" ") + 1);
    while (str.at(0) == ' ')
        str.erase(0,1);
}

objModel::objModel(vec3 pos, float scale, std::string file) : object()
{
    this->pos.x = pos.x;
    this->pos.y = pos.y;
    this->pos.z = pos.z;
    this->scale = scale;
    this->precision = 1;

    std::ifstream fichier(file.c_str(), std::ios::in);
    if (fichier)
    {
        std::string ligne;
        while(getline(fichier,ligne))
        {
            if (ligne.length() > 2)
            {
                if (ligne.at(0) == 'v' && ligne.at(1) == ' ')
                {
                    nextNum(ligne);
                    float x = atof(ligne.c_str());
                    nextNum(ligne);
                    float y = atof(ligne.c_str());
                    nextNum(ligne);
                    float z = atof(ligne.c_str());
                    vec3 v(x,y,z);
                    allpoint.push_back(v);
                }
                else if (ligne.at(0) == 'f')
                {
                    nextNum(ligne);
                    int a = atoi(ligne.c_str());
                    nextNum(ligne);
                    int b = atoi(ligne.c_str());
                    nextNum(ligne);
                    int c = atoi(ligne.c_str());
                    model.push_back(allpoint.at(a - 1));
                    model.push_back(allpoint.at(b - 1));
                    model.push_back(allpoint.at(c - 1));
                }
            }
        }
    }
    else
        std::cout << "error : file " + file << std::endl;
}

objModel::~objModel()
{
    //dtor
}

void objModel::setPrecision(int i)
{
    this->precision = i;
}

void        objModel::draw()
{
    glBegin(GL_TRIANGLES);

    glColor3ub(255,0,255);
    int i = 0;
    while (i < model.size())
    {
        glVertex3d((model.at(i).x + pos.x) * scale,(model.at(i).y + pos.y) * scale,(model.at(i).z + pos.z) * scale);
        ++i;
    }
    glEnd();
}
